import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class BufferToText {
    public static final int BSIZE = 1024;

    public static void main(String[] args) {
        try (FileChannel fc = new FileOutputStream("data2.txt").getChannel()) {
            fc.write(ByteBuffer.wrap("Some text".getBytes()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
        try (FileChannel fc = new FileInputStream("data2.txt").getChannel()) {
            fc.read(buffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        buffer.flip();
        // 无法运行
        System.out.println(buffer.asCharBuffer());
        // 使用默认系统默认编码解码
        buffer.rewind();
        final String encoding = System.getProperty("file.encoding");
        System.out.println("Decoded using " + encoding + ": " + Charset.forName(encoding).decode(buffer));

        // 编码和打印
        try (FileChannel fc = new FileOutputStream("data2.txt").getChannel()) {
            fc.write(ByteBuffer.wrap("Some text".getBytes("UTF-16BE")));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        buffer.clear();
        try (FileChannel fc = new FileInputStream("data2.txt").getChannel()) {
            fc.read(buffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        buffer.flip();
        System.out.println(buffer.asCharBuffer());
        // 通过CharBuffer写入
        buffer = ByteBuffer.allocate(24);
        buffer.asCharBuffer().put("Some text");

        try (FileChannel fc = new FileOutputStream("data2.txt").getChannel()) {
            fc.write(buffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 读取和显示
        buffer.clear();

        try (FileChannel fc = new FileInputStream("data2.txt").getChannel()) {
            fc.read(buffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        buffer.flip();
        System.out.println(buffer.asCharBuffer());
    }
}
